package com.sun.androidexerciseproject.function.music.service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Environment;
import android.os.IBinder;

import java.io.File;
import java.io.IOException;

public class MediaService extends Service {
    private static final String BASE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "Music";
    private static String[] mMusics;

    static {
        File file = new File(BASE_PATH);
        if (file.exists()) {
            String[] musics = file.list();
            if (null != musics) {
                int len = musics.length;
                mMusics = new String[len];
                for (int i = 0; i < len; i++) {
                    mMusics[i] = BASE_PATH + File.separator + musics[i];
                }
            }
        }
    }

    private int i = 0;
    private MyBinder myBinder = new MyBinder();
    private MediaPlayer mediaPlayer = new MediaPlayer();

    public MediaService() {

        initMediaPlayer();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return myBinder;
    }

    private void initMediaPlayer() {
        if (null != mMusics) {
            try {
                mediaPlayer.setDataSource(mMusics[i]);
                mediaPlayer.prepare();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            mediaPlayer = null;
        }
    }

    public class MyBinder extends Binder {
        public void play() {
            if (null != mediaPlayer && !mediaPlayer.isPlaying()) {
                mediaPlayer.start();
            }
        }

        public void pause() {
            if (null != mediaPlayer && mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
            }
        }

        public void precious() {
            if (null != mediaPlayer) {
                mediaPlayer.reset();
                if (i == 0) {
                    i = mMusics.length;
                }
                i = (i - 1) % mMusics.length;
                initMediaPlayer();
                play();
            }
        }

        public void next() {
            if (null != mediaPlayer) {
                mediaPlayer.reset();
                i = (i + 1) % mMusics.length;
                initMediaPlayer();
                play();
            }

        }

        public void close() {
            if (null != mediaPlayer) {
                mediaPlayer.stop();
                mediaPlayer.release();
            }
        }
    }
}
